package user

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/xinglou123/pkg/os/conv"
	"github.com/xinglou123/pkg/os/md5"
	"github.com/xinglou123/pkg/utils"
	"github.com/xinglou123/pkg/validator"
	"net/http"
)

type ApiUser struct {
}

func (au ApiUser) Router(router *gin.Engine) {
	r := router.Group("user")
	r.POST("login", au.userSignin)
	r.POST("logout", au.userSignout)
	r.POST("reg", au.userSignup)
	r.POST("repassword", au.userRepassword)
	r.GET("list", au.userList)
	r.GET("info/:id", au.userInfoWithId)
	r.GET("session", au.userSession)
	r.POST("edit", au.userEdit)
	r.POST("delete/:id", au.userDelete)
	r.POST("create", au.userAdd)

}
func (au ApiUser) userSignin(ctx *gin.Context) {
	result := utils.NewResponse()
	defer ctx.JSON(http.StatusOK, result)

	username := ctx.DefaultPostForm("username", "")
	password := ctx.DefaultPostForm("password", "")
	if len(username) == 0 || len(password) == 0 {
		result.Code = 100
		result.Msg = "用户名密码不能为空"
		return
	}
	user, err := UserService.Signin(username, password)
	if err != nil {
		result.Code = 100
		result.Msg = err.Error()
		return
	}
	params := map[string]interface{}{}
	params["uid"] = user.Id
	params["name"] = user.Nick
	params["avatar"] = user.Avatar
	params["token"] = user.Password

	result.Data = params
	result.Code = 200
	result.Msg = "登录成功"

	return
}
func (au ApiUser) userSignout(ctx *gin.Context) {
	result := utils.NewResponse()
	defer ctx.JSON(http.StatusOK, result)

	result.Code = 200
	result.Msg = "退出成功"

	return
}
func (au ApiUser) userSignup(ctx *gin.Context) {
	result := utils.NewResponse()
	defer ctx.JSON(http.StatusOK, result)

	var user User
	if error := ctx.Bind(&user); error != nil {
		result.Code = 100
		result.Msg = "参数异常"
		return
	}
	uuser, err := UserService.Add(user)
	if err != nil {
		result.Code = 100
		result.Msg = err.Error()
		return
	}
	result.Msg = "恭喜你注册成功"
	result.Data = uuser
	return
}
func (au ApiUser) userRepassword(ctx *gin.Context) {
	result := utils.NewResponse()
	defer ctx.JSON(http.StatusOK, result)

	type ReqData struct {
		Userid      string `xorm:"char(50)" form:"userid"`
		Oldpassword string `xorm:"char(50)" form:"oldpassword"`
		Password    string `xorm:"char(50)" form:"password"`
		Repassword  string `xorm:"char(50)" form:"repassword"`
	}
	var reqData ReqData
	if error := ctx.Bind(&reqData); error != nil {
		result.Code = 100
		result.Msg = error.Error()
		return
	}
	fmt.Println(reqData)
	if len(reqData.Userid) == 0 {
		result.Code = 100
		result.Msg = "用户不存在"
		return
	}
	if !validator.IsPassword(reqData.Oldpassword) || !validator.IsPassword(reqData.Password) {
		result.Code = 100
		result.Msg = "字母开头，允许6-20字节，允许字母数字特殊字符"
		return
	}
	if reqData.Password != reqData.Repassword {
		result.Code = 100
		result.Msg = "两次密码不一致"
		return
	}
	//var user model.User
	user, err := UserService.One(conv.Int64(reqData.Userid))
	if err != nil {
		result.Code = 100
		result.Msg = err.Error()
		return
	}
	fmt.Println(user)
	pwd := md5.CryptPassword(reqData.Oldpassword, user.Salt)
	fmt.Println(pwd)
	if pwd != user.Password {
		result.Code = 100
		result.Msg = "旧密码不正确,请重试"
		return
	}

	salt := md5.GenRandomString(6, true)
	user.Password = md5.CryptPassword(reqData.Password, salt)
	user.Salt = salt
	uuuser, err := UserService.Update(user)
	if err != nil {
		result.Code = 100
		result.Msg = err.Error()
		return
	}
	result.Msg = "密码修改成功"
	result.Data = uuuser
	return
}

// @Title /user/list
// @API_GROUP user
// @Description 查询列表接口
// @Param   title     query   int true       "title"
// @Param   page     query   int true       "page"
// @Param   pageSize     query   int true       "pageSize"
// @Success 200 {object}
// @router /user/list [get]
func (au ApiUser) userList(ctx *gin.Context) {
	result := utils.NewResponse()
	defer ctx.JSON(http.StatusOK, result)

	params := map[string]interface{}{}
	params["path"] = ctx.DefaultQuery("path", "")
	params["user_id"] = ctx.DefaultQuery("user_id", "")
	params["limit"] = ctx.DefaultQuery("limit", "10")
	params["page"] = ctx.DefaultQuery("page", "1")

	list, page, err := UserService.Query(params)
	if err != nil {
		result.Code = 100
		result.Msg = err.Error()
		return
	}
	data := map[string]interface{}{}
	data["lists"] = list
	data["page"] = page

	result.Data = data
	result.Code = 200
	result.Msg = "ok"

	return

}

// @Title /user/info/:id
// @API_GROUP user
// @Description 查询列表接口
// @Param   uid     query   string false       "uid"
// @Success 200 {object}
// @router /user/info/:id [get]
func (au ApiUser) userInfoWithId(ctx *gin.Context) {
	result := utils.NewResponse()
	defer ctx.JSON(http.StatusOK, result)

	uid := ctx.Param("id")
	if uid == "" {
		result.Code = 100
		result.Msg = "参数异常"
		return
	}
	user, err := UserService.One(conv.Int64(uid))
	if err != nil {
		result.Code = 100
		result.Msg = err.Error()
		return
	}
	result.Data = user
	return
}

// @Title /user/session
// @API_GROUP user
// @Description 查询列表接口
// @Param   uid     query   string false       "uid"
// @Success 200 {object}
// @router /user/info/:id [get]
func (au ApiUser) userSession(ctx *gin.Context) {
	result := utils.NewResponse()
	defer ctx.JSON(http.StatusOK, result)

	//uid := ctx.Param("id")
	//if uid == "" {
	//	result.Code = 100
	//	result.Msg = "参数异常"
	//	return
	//}
	user, err := UserService.One(conv.Int64(1))
	if err != nil {
		result.Code = 100
		result.Msg = err.Error()
		return
	}
	result.Data = user
	return
}

// @Title user add
// @API_GROUP user
// @Description 添加接口
// @Param   SignupdateForm
// @Success 200 {object}
// @router /user/add [post]
func (au ApiUser) userAdd(ctx *gin.Context) {
	result := utils.NewResponse()
	defer ctx.JSON(http.StatusOK, result)

	var user User
	if error := ctx.Bind(&user); error != nil {
		result.Code = 100
		result.Msg = "参数异常"
		return
	}
	uuser, err := UserService.Add(user)
	if err != nil {
		result.Code = 100
		result.Msg = err.Error()
		return
	}
	result.Msg = "添加用户成功"
	result.Data = uuser
	return

}

// @Title userModel Delete
// @API_GROUP user
// @Description 删除接口
// @Param   id     query   int true       "id"
// @Success 200 {object}
// @router /user/delete [post]
func (au ApiUser) userDelete(ctx *gin.Context) {
	result := utils.NewResponse()
	defer ctx.JSON(http.StatusOK, result)

	uid := ctx.Param("id")
	if uid == "" {
		result.Code = 100
		result.Msg = "参数异常"
		return
	}
	_, err := UserService.Delete(conv.Int64(uid))
	if err != nil {
		result.Code = 100
		result.Msg = "删除用户失败"
		return
	}
	result.Msg = "删除用户成功"
	return
}

// @Title userModel edit
// @API_GROUP user
// @Description 编辑接口
// @Param   SignupdateForm
// @Success 200 {object}
// @router /user/edit [post]
func (au ApiUser) userEdit(ctx *gin.Context) {
	result := utils.NewResponse()
	defer ctx.JSON(http.StatusOK, result)

	var user User
	if err := ctx.Bind(&user); err != nil {
		result.Code = 100
		result.Msg = err.Error()
		return
	}
	if user.Id == 0 {
		result.Code = 100
		result.Msg = "请选择要修改的用户"
		return
	}
	_, err := UserService.Update(user)
	if err != nil {
		result.Code = 100
		result.Msg = "修改用户失败"
		return
	}
	result.Msg = "修改用户成功"
	return
}
